<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="机器学习,决策树,">










<meta name="description" content="1. 简介 决策树(Decision Tree）是在已知各种情况发生概率的基础上，通过构成决策树来求取净现值的期望值大于等于零的概率，评价项目风险，判断其可行性的决策分析方法，是直观运用概率分析的一种图解法。由于这种决策分支画成图形很像一棵树的枝干，故称决策树。在机器学习中，决策树是一个预测模型，他代表的是对象属性与对象值之间的一种映射关系。Entropy = 系统的凌乱程度，使用算法ID3, C">
<meta name="keywords" content="机器学习,决策树">
<meta property="og:type" content="article">
<meta property="og:title" content="[机器学习实战]决策树">
<meta property="og:url" content="http://mantoudev.com/[机器学习实战]决策树/index.html">
<meta property="og:site_name" content="MantouDev">
<meta property="og:description" content="1. 简介 决策树(Decision Tree）是在已知各种情况发生概率的基础上，通过构成决策树来求取净现值的期望值大于等于零的概率，评价项目风险，判断其可行性的决策分析方法，是直观运用概率分析的一种图解法。由于这种决策分支画成图形很像一棵树的枝干，故称决策树。在机器学习中，决策树是一个预测模型，他代表的是对象属性与对象值之间的一种映射关系。Entropy = 系统的凌乱程度，使用算法ID3, C">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/%E5%86%B3%E7%AD%96%E6%A0%91-%E6%B5%81%E7%A8%8B%E5%9B%BE.jpg">
<meta property="og:image" content="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/DT_%E6%B5%B7%E6%B4%8B%E7%94%9F%E7%89%A9%E6%95%B0%E6%8D%AE.png">
<meta property="og:image" content="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/%E7%86%B5%E7%9A%84%E8%AE%A1%E7%AE%97%E5%85%AC%E5%BC%8F.jpg">
<meta property="og:updated_time" content="2018-11-27T14:34:03.565Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[机器学习实战]决策树">
<meta name="twitter:description" content="1. 简介 决策树(Decision Tree）是在已知各种情况发生概率的基础上，通过构成决策树来求取净现值的期望值大于等于零的概率，评价项目风险，判断其可行性的决策分析方法，是直观运用概率分析的一种图解法。由于这种决策分支画成图形很像一棵树的枝干，故称决策树。在机器学习中，决策树是一个预测模型，他代表的是对象属性与对象值之间的一种映射关系。Entropy = 系统的凌乱程度，使用算法ID3, C">
<meta name="twitter:image" content="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/%E5%86%B3%E7%AD%96%E6%A0%91-%E6%B5%81%E7%A8%8B%E5%9B%BE.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://mantoudev.com/[机器学习实战]决策树/">





  <title>[机器学习实战]决策树 | MantouDev</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-129870378-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">MantouDev</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">🐈 👀</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://mantoudev.com/[机器学习实战]决策树/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mantou">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="MantouDev">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">[机器学习实战]决策树</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-21T11:27:00+08:00">
                2018-04-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/[机器学习实战]决策树/" class="leancloud_visitors" data-flag-title="[机器学习实战]决策树">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-简介"><a href="#1-简介" class="headerlink" title="1. 简介"></a>1. 简介</h2><p> 决策树(Decision Tree）是在已知各种情况发生概率的基础上，通过构成决策树来求取净现值的期望值大于等于零的概率，评价项目风险，判断其可行性的决策分析方法，是直观运用概率分析的一种图解法。由于这种决策分支画成图形很像一棵树的枝干，故称决策树。在机器学习中，决策树是一个预测模型，他代表的是<code>对象属性</code>与<code>对象值</code>之间的一种映射关系。Entropy = 系统的凌乱程度，使用算法ID3, C4.5和C5.0生成树算法使用熵。这一度量是基于信息学理论中熵的概念。<br>   <a id="more"></a></p>
<p>决策树是一种树形结构，其中每个内部节点表示一个属性上的测试，每个分支代表一个测试输出，每个叶节点代表一种类别。</p>
<p>决策树学习通常包括 3 个步骤：</p>
<ul>
<li>特征选择</li>
<li>决策树的生成</li>
<li>决策树的修剪</li>
</ul>
<h3 id="1-1-决策树场景"><a href="#1-1-决策树场景" class="headerlink" title="1.1 决策树场景"></a>1.1 决策树场景</h3><h5 id="场景一：二十个问题"><a href="#场景一：二十个问题" class="headerlink" title="场景一：二十个问题"></a>场景一：二十个问题</h5><p>有一个叫 “二十个问题” 的游戏，游戏规则很简单：参与游戏的一方在脑海中想某个事物，其他参与者向他提问，只允许提 20 个问题，问题的答案也只能用对或错回答。问问题的人通过推断分解，逐步缩小待猜测事物的范围，最后得到游戏的答案。</p>
<h5 id="场景二：邮件分类"><a href="#场景二：邮件分类" class="headerlink" title="场景二：邮件分类"></a>场景二：邮件分类</h5><p>一个邮件分类系统，大致工作流程如下：</p>
<p><img src="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/%E5%86%B3%E7%AD%96%E6%A0%91-%E6%B5%81%E7%A8%8B%E5%9B%BE.jpg" alt="image"></p>
<p>首先检测发送邮件域名地址。如果地址为 myEmployer.com, 则将其放在分类 “无聊时需要阅读的邮件”中。<br>如果邮件不是来自这个域名，则检测邮件内容里是否包含单词 “曲棍球” , 如果包含则将邮件归类到 “需要及时处理的朋友邮件”,<br>如果不包含则将邮件归类到 “无需阅读的垃圾邮件” 。</p>
<h3 id="1-2-定义"><a href="#1-2-定义" class="headerlink" title="1.2 定义"></a>1.2 定义</h3><p>分类决策树模型是一种描述对实例进行分类的树形结构。决策树由<code>结点（node）</code>和<code>有向边（directed edge</code>）组成。</p>
<p>结点有两种类型：</p>
<ul>
<li>内部结点（internal node）：表示一个特征或属性。</li>
<li>叶结点（leaf： node）：表示一个类。</li>
</ul>
<p>用决策树分类，从根节点开始，对实例的某一特征进行测试，根据测试结果，将实例分配到其子结点；这时，每一个子结点对应着该特征的一个取值。如此递归地对实例进行测试并分配，直至达到叶结点。最后将实例分配到叶结点的类中。</p>
<h2 id="2-决策树原理"><a href="#2-决策树原理" class="headerlink" title="2. 决策树原理"></a>2. 决策树原理</h2><ul>
<li><strong>熵</strong>：<br>熵（entropy）指的是体系的混乱的程度，在不同的学科中也有引申出的更为具体的定义，是各领域十分重要的参量。</li>
<li><p><strong>信息熵（香农熵）</strong>：<br>是一种信息的度量方式，表示信息的混乱程度，也就是说：信息越有序，信息熵越低。例如：火柴有序放在火柴盒里，熵值很低，相反，熵值很高。</p>
</li>
<li><p><strong>信息增益</strong>：<br>在划分数据集前后信息发生的变化称为信息增益。</p>
</li>
</ul>
<h3 id="2-1-工作原理"><a href="#2-1-工作原理" class="headerlink" title="2.1 工作原理"></a>2.1 工作原理</h3><p>我们使用 createBranch() 方法构造一个决策树，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">检测数据集中的所有数据的分类标签是否相同:</span><br><span class="line">    If so return 类标签</span><br><span class="line">    Else:</span><br><span class="line">        寻找划分数据集的最好特征（划分之后信息熵最小，也就是信息增益最大的特征）</span><br><span class="line">        划分数据集</span><br><span class="line">        创建分支节点</span><br><span class="line">            for 每个划分的子集</span><br><span class="line">                调用函数 createBranch （创建分支的函数）并增加返回结果到分支节点中</span><br><span class="line">        return 分支节点</span><br></pre></td></tr></table></figure>
<h3 id="2-2-决策树开发流程"><a href="#2-2-决策树开发流程" class="headerlink" title="2.2 决策树开发流程"></a>2.2 决策树开发流程</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1. 收集数据：可以使用任何方法。</span><br><span class="line">2. 准备数据：树构造算法只适用于标称型数据，因此数值型数据必须离散化。</span><br><span class="line">3. 分析数据：可以使用任何方法，构造树完成之后，我们应该检查图形是否符合预期。</span><br><span class="line">4. 训练算法：构造树的数据结构。</span><br><span class="line">5. 测试算法：使用经验树计算错误率。（经验树没有搜索到较好的资料，有兴趣的同学可以来补充）</span><br><span class="line">6. 使用算法：此步骤可以适用于任何监督学习算法，而使用决策树可以更好地理解数据的内在含义。</span><br></pre></td></tr></table></figure>
<h3 id="2-3-决策树算法特点"><a href="#2-3-决策树算法特点" class="headerlink" title="2.3 决策树算法特点"></a>2.3 决策树算法特点</h3><ul>
<li><strong>优点</strong>：计算复杂度不高，输出结果易于理解，对中间值的缺失不敏感，可以处理不相关特征数据。</li>
<li><strong>缺点</strong>：可能会产生过度匹配问题。<br>适用数据类型：数值型和标称型。</li>
</ul>
<h2 id="3-实战案例"><a href="#3-实战案例" class="headerlink" title="3. 实战案例"></a>3. 实战案例</h2><h3 id="3-1-项目概述"><a href="#3-1-项目概述" class="headerlink" title="3.1 项目概述"></a>3.1 项目概述</h3><p>根据以下 2 个特征，将动物分成两类：鱼类和非鱼类。</p>
<p><strong>特征</strong>：</p>
<ul>
<li>不浮出水面是否可以生存</li>
<li>是否有脚蹼</li>
</ul>
<h3 id="3-2-开发流程"><a href="#3-2-开发流程" class="headerlink" title="3.2 开发流程"></a>3.2 开发流程</h3><h4 id="1-收集数据"><a href="#1-收集数据" class="headerlink" title="(1) 收集数据"></a>(1) 收集数据</h4><blockquote>
<p>可以使用任何方法</p>
</blockquote>
<p><img src="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/DT_%E6%B5%B7%E6%B4%8B%E7%94%9F%E7%89%A9%E6%95%B0%E6%8D%AE.png" alt="image"></p>
<p>我们利用 createDataSet() 函数输入数据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">def createDataSet():</span><br><span class="line">    dataSet = [[1, 1, &apos;yes&apos;],</span><br><span class="line">            [1, 1, &apos;yes&apos;],</span><br><span class="line">            [1, 0, &apos;no&apos;],</span><br><span class="line">            [0, 1, &apos;no&apos;],</span><br><span class="line">            [0, 1, &apos;no&apos;]]</span><br><span class="line">    labels = [&apos;no surfacing&apos;, &apos;flippers&apos;]</span><br><span class="line">    return dataSet, labels</span><br></pre></td></tr></table></figure>
<h4 id="2-准备数据"><a href="#2-准备数据" class="headerlink" title="(2) 准备数据"></a>(2) 准备数据</h4><blockquote>
<p>树构造算法只适用于标称型数据，因此数值型数据必须离散化</p>
</blockquote>
<p>此处，由于我们输入的数据本身就是离散化数据，所以这一步就省略了。</p>
<h4 id="（3）-分析数据"><a href="#（3）-分析数据" class="headerlink" title="（3） 分析数据"></a>（3） 分析数据</h4><blockquote>
<p>可以使用任何方法，构造树完成之后，我们应该检查图形是否符合预期</p>
</blockquote>
<p><img src="https://raw.love2.io/gaolinjie/MachineLearning/b4e6199f40af19a2ef53d694ccedab515aac7ffe/images/3.DecisionTree/%E7%86%B5%E7%9A%84%E8%AE%A1%E7%AE%97%E5%85%AC%E5%BC%8F.jpg" alt="image"></p>
<h5 id="计算给定数据集的香农熵的函数"><a href="#计算给定数据集的香农熵的函数" class="headerlink" title="计算给定数据集的香农熵的函数"></a>计算给定数据集的香农熵的函数</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">def calcShannonEnt(dataSet):</span><br><span class="line">    # 求list的长度，表示计算参与训练的数据量</span><br><span class="line">    numEntries = len(dataSet)</span><br><span class="line">    # 计算分类标签label出现的次数</span><br><span class="line">    labelCounts = &#123;&#125;</span><br><span class="line">    # the the number of unique elements and their occurance</span><br><span class="line">    for featVec in dataSet:</span><br><span class="line">        # 将当前实例的标签存储，即每一行数据的最后一个数据代表的是标签</span><br><span class="line">        currentLabel = featVec[-1]</span><br><span class="line">        # 为所有可能的分类创建字典，如果当前的键值不存在，则扩展字典并将当前键值加入字典。每个键值都记录了当前类别出现的次数。</span><br><span class="line">        if currentLabel not in labelCounts.keys():</span><br><span class="line">            labelCounts[currentLabel] = 0</span><br><span class="line">        labelCounts[currentLabel] += 1</span><br><span class="line"></span><br><span class="line">    # 对于 label 标签的占比，求出 label 标签的香农熵</span><br><span class="line">    shannonEnt = 0.0</span><br><span class="line">    for key in labelCounts:</span><br><span class="line">        # 使用所有类标签的发生频率计算类别出现的概率。</span><br><span class="line">        prob = float(labelCounts[key])/numEntries</span><br><span class="line">        # 计算香农熵，以 2 为底求对数</span><br><span class="line">        shannonEnt -= prob * log(prob, 2)</span><br><span class="line">    return shannonEnt</span><br></pre></td></tr></table></figure>
<h5 id="按照给定特征划分数据集"><a href="#按照给定特征划分数据集" class="headerlink" title="按照给定特征划分数据集"></a>按照给定特征划分数据集</h5><p>将指定特征的特征值等于 value 的行剩下列作为子数据集。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">def splitDataSet(dataSet, index, value):</span><br><span class="line">    &quot;&quot;&quot;splitDataSet(通过遍历dataSet数据集，求出index对应的colnum列的值为value的行)</span><br><span class="line">        就是依据index列进行分类，如果index列的数据等于 value的时候，就要将 index 划分到我们创建的新的数据集中</span><br><span class="line">    Args:</span><br><span class="line">        dataSet 数据集                 待划分的数据集</span><br><span class="line">        index 表示每一行的index列        划分数据集的特征</span><br><span class="line">        value 表示index列对应的value值   需要返回的特征的值。</span><br><span class="line">    Returns:</span><br><span class="line">        index列为value的数据集【该数据集需要排除index列】</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    retDataSet = []</span><br><span class="line">    for featVec in dataSet:</span><br><span class="line">        # index列为value的数据集【该数据集需要排除index列】</span><br><span class="line">        # 判断index列的值是否为value</span><br><span class="line">        if featVec[index] == value:</span><br><span class="line">            # chop out index used for splitting</span><br><span class="line">            # [:index]表示前index行，即若 index 为2，就是取 featVec 的前 index 行</span><br><span class="line">            reducedFeatVec = featVec[:index]</span><br><span class="line">            &apos;&apos;&apos;</span><br><span class="line">            请百度查询一下： extend和append的区别</span><br><span class="line">            list.append(object) 向列表中添加一个对象object</span><br><span class="line">            list.extend(sequence) 把一个序列seq的内容添加到列表中</span><br><span class="line">            1、使用append的时候，是将new_media看作一个对象，整体打包添加到music_media对象中。</span><br><span class="line">            2、使用extend的时候，是将new_media看作一个序列，将这个序列和music_media序列合并，并放在其后面。</span><br><span class="line">            result = []</span><br><span class="line">            result.extend([1,2,3])</span><br><span class="line">            print result</span><br><span class="line">            result.append([4,5,6])</span><br><span class="line">            print result</span><br><span class="line">            result.extend([7,8,9])</span><br><span class="line">            print result</span><br><span class="line">            结果：</span><br><span class="line">            [1, 2, 3]</span><br><span class="line">            [1, 2, 3, [4, 5, 6]]</span><br><span class="line">            [1, 2, 3, [4, 5, 6], 7, 8, 9]</span><br><span class="line">            &apos;&apos;&apos;</span><br><span class="line">            reducedFeatVec.extend(featVec[index+1:])</span><br><span class="line">            # [index+1:]表示从跳过 index 的 index+1行，取接下来的数据</span><br><span class="line">            # 收集结果值 index列为value的行【该行需要排除index列】</span><br><span class="line">            retDataSet.append(reducedFeatVec)</span><br><span class="line">    return retDataSet</span><br></pre></td></tr></table></figure>
<h5 id="选择最好的数据集划分方式"><a href="#选择最好的数据集划分方式" class="headerlink" title="选择最好的数据集划分方式"></a>选择最好的数据集划分方式</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">def chooseBestFeatureToSplit(dataSet):</span><br><span class="line">    &quot;&quot;&quot;chooseBestFeatureToSplit(选择最好的特征)</span><br><span class="line"></span><br><span class="line">    Args:</span><br><span class="line">        dataSet 数据集</span><br><span class="line">    Returns:</span><br><span class="line">        bestFeature 最优的特征列</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    # 求第一行有多少列的 Feature, 最后一列是label列嘛</span><br><span class="line">    numFeatures = len(dataSet[0]) - 1</span><br><span class="line">    # 数据集的原始信息熵</span><br><span class="line">    baseEntropy = calcShannonEnt(dataSet)</span><br><span class="line">    # 最优的信息增益值, 和最优的Featurn编号</span><br><span class="line">    bestInfoGain, bestFeature = 0.0, -1</span><br><span class="line">    # iterate over all the features</span><br><span class="line">    for i in range(numFeatures):</span><br><span class="line">        # create a list of all the examples of this feature</span><br><span class="line">        # 获取对应的feature下的所有数据</span><br><span class="line">        featList = [example[i] for example in dataSet]</span><br><span class="line">        # get a set of unique values</span><br><span class="line">        # 获取剔重后的集合，使用set对list数据进行去重</span><br><span class="line">        uniqueVals = set(featList)</span><br><span class="line">        # 创建一个临时的信息熵</span><br><span class="line">        newEntropy = 0.0</span><br><span class="line">        # 遍历某一列的value集合，计算该列的信息熵</span><br><span class="line">        # 遍历当前特征中的所有唯一属性值，对每个唯一属性值划分一次数据集，计算数据集的新熵值，并对所有唯一特征值得到的熵求和。</span><br><span class="line">        for value in uniqueVals:</span><br><span class="line">            subDataSet = splitDataSet(dataSet, i, value)</span><br><span class="line">            # 计算概率</span><br><span class="line">            prob = len(subDataSet)/float(len(dataSet))</span><br><span class="line">            # 计算信息熵</span><br><span class="line">            newEntropy += prob * calcShannonEnt(subDataSet)</span><br><span class="line">        # gain[信息增益]: 划分数据集前后的信息变化， 获取信息熵最大的值</span><br><span class="line">        # 信息增益是熵的减少或者是数据无序度的减少。最后，比较所有特征中的信息增益，返回最好特征划分的索引值。</span><br><span class="line">        infoGain = baseEntropy - newEntropy</span><br><span class="line">        print &apos;infoGain=&apos;, infoGain, &apos;bestFeature=&apos;, i, baseEntropy, newEntropy</span><br><span class="line">        if (infoGain &gt; bestInfoGain):</span><br><span class="line">            bestInfoGain = infoGain</span><br><span class="line">            bestFeature = i</span><br><span class="line">    return bestFeature</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Q：上面的 newEntropy 为什么是根据子集计算的呢？<br>A ：因为我们在根据一个特征计算香农熵的时候，该特征的分类值是相同，这个特征这个分类的香农熵为 0；<br>这就是为什么计算新的香农熵的时候使用的是子集。</p>
</blockquote>
<h4 id="（4）训练算法"><a href="#（4）训练算法" class="headerlink" title="（4）训练算法"></a>（4）训练算法</h4><blockquote>
<p>构造树的数据结构</p>
</blockquote>
<p>创建树的函数代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">def createTree(dataSet, labels):</span><br><span class="line">    classList = [example[-1] for example in dataSet]</span><br><span class="line">    # 如果数据集的最后一列的第一个值出现的次数=整个集合的数量，也就说只有一个类别，就只直接返回结果就行</span><br><span class="line">    # 第一个停止条件：所有的类标签完全相同，则直接返回该类标签。</span><br><span class="line">    # count() 函数是统计括号中的值在list中出现的次数</span><br><span class="line">    if classList.count(classList[0]) == len(classList):</span><br><span class="line">        return classList[0]</span><br><span class="line">    # 如果数据集只有1列，那么最初出现label次数最多的一类，作为结果</span><br><span class="line">    # 第二个停止条件：使用完了所有特征，仍然不能将数据集划分成仅包含唯一类别的分组。</span><br><span class="line">    if len(dataSet[0]) == 1:</span><br><span class="line">        return majorityCnt(classList)</span><br><span class="line"></span><br><span class="line">    # 选择最优的列，得到最优列对应的label含义</span><br><span class="line">    bestFeat = chooseBestFeatureToSplit(dataSet)</span><br><span class="line">    # 获取label的名称</span><br><span class="line">    bestFeatLabel = labels[bestFeat]</span><br><span class="line">    # 初始化myTree</span><br><span class="line">    myTree = &#123;bestFeatLabel: &#123;&#125;&#125;</span><br><span class="line">    # 注：labels列表是可变对象，在PYTHON函数中作为参数时传址引用，能够被全局修改</span><br><span class="line">    # 所以这行代码导致函数外的同名变量被删除了元素，造成例句无法执行，提示&apos;no surfacing&apos; is not in list</span><br><span class="line">    del(labels[bestFeat])</span><br><span class="line">    # 取出最优列，然后它的branch做分类</span><br><span class="line">    featValues = [example[bestFeat] for example in dataSet]</span><br><span class="line">    uniqueVals = set(featValues)</span><br><span class="line">    for value in uniqueVals:</span><br><span class="line">        # 求出剩余的标签label</span><br><span class="line">        subLabels = labels[:]</span><br><span class="line">        # 遍历当前选择特征包含的所有属性值，在每个数据集划分上递归调用函数createTree()</span><br><span class="line">        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)</span><br><span class="line">        # print &apos;myTree&apos;, value, myTree</span><br><span class="line">    return myTree</span><br></pre></td></tr></table></figure>
<h4 id="（5）测试算法"><a href="#（5）测试算法" class="headerlink" title="（5）测试算法"></a>（5）测试算法</h4><blockquote>
<p>使用决策树执行分类<br>代码如下：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">def classify(inputTree, featLabels, testVec):</span><br><span class="line">    &quot;&quot;&quot;classify(给输入的节点，进行分类)</span><br><span class="line"></span><br><span class="line">    Args:</span><br><span class="line">        inputTree  决策树模型</span><br><span class="line">        featLabels Feature标签对应的名称</span><br><span class="line">        testVec    测试输入的数据</span><br><span class="line">    Returns:</span><br><span class="line">        classLabel 分类的结果值，需要映射label才能知道名称</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    # 获取tree的根节点对于的key值</span><br><span class="line">    firstStr = inputTree.keys()[0]</span><br><span class="line">    # 通过key得到根节点对应的value</span><br><span class="line">    secondDict = inputTree[firstStr]</span><br><span class="line">    # 判断根节点名称获取根节点在label中的先后顺序，这样就知道输入的testVec怎么开始对照树来做分类</span><br><span class="line">    featIndex = featLabels.index(firstStr)</span><br><span class="line">    # 测试数据，找到根节点对应的label位置，也就知道从输入的数据的第几位来开始分类</span><br><span class="line">    key = testVec[featIndex]</span><br><span class="line">    valueOfFeat = secondDict[key]</span><br><span class="line">    print &apos;+++&apos;, firstStr, &apos;xxx&apos;, secondDict, &apos;---&apos;, key, &apos;&gt;&gt;&gt;&apos;, valueOfFeat</span><br><span class="line">    # 判断分枝是否结束: 判断valueOfFeat是否是dict类型</span><br><span class="line">    if isinstance(valueOfFeat, dict):</span><br><span class="line">        classLabel = classify(valueOfFeat, featLabels, testVec)</span><br><span class="line">    else:</span><br><span class="line">        classLabel = valueOfFeat</span><br><span class="line">    return classLabel</span><br></pre></td></tr></table></figure>
<h4 id="（6）使用算法"><a href="#（6）使用算法" class="headerlink" title="（6）使用算法"></a>（6）使用算法</h4><blockquote>
<p>此步骤可以适用于任何监督学习算法，而使用决策树可以更好地理解数据的内在含义。</p>
</blockquote>
<p>构造决策树是很耗时的任务，即使很小的数据集也要花费几秒。如果用创建好的决策树解决分类问题就可以很快完成。</p>
<p>因此为了节省计算时间，最好能每次执行分类时调用已经构造好的决策树，为了解决这个问题，需要使用Python模块<code>pickle</code>序列化对象。序列化对象可以在磁盘上保存对象，并在需要的时候读取出来。任何对象都可以执行序列化，包括字典对象。</p>
<p>下面代码是使用pickle模块存储决策树：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">def storeTree(inputTree, filename):</span><br><span class="line">    impory pickle</span><br><span class="line">    fw = open(filename, &apos;w&apos;)</span><br><span class="line">    pickle.dump(inputTree, fw)</span><br><span class="line">    fw.close()</span><br><span class="line"></span><br><span class="line">def grabTree(filename):</span><br><span class="line">    import pickle</span><br><span class="line">    fr = open(filename)</span><br><span class="line">    return pickle.load(fr)</span><br></pre></td></tr></table></figure>
<p>通过上面的代码我们可以把分类器存储在硬盘上，而不用每次对数据分类时重新学习一遍，这也是决策树的优点之一。++K-近邻算法就无法持久化分类器++。</p>
<hr>
<p>[1] 决策树维基百科：  <a href="https://zh.wikipedia.org/wiki/%E5%86%B3%E7%AD%96%E6%A0%91" target="_blank" rel="noopener">https://zh.wikipedia.org/wiki/%E5%86%B3%E7%AD%96%E6%A0%91</a><br>[2]《机器学习实战》  –  Peter Harrington<br>[3]《机器学习》 –  周志华</p>

      
    </div>
    
    
    

    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">
  <p><span>文章作者:</span><a href="/" title="访问 Mantou 的个人博客">Mantou</a></p>
  <p><span>最后更新:</span>2018年11月27日 22:11:03</p>
  <p><span>原始链接:</span><a href="/[机器学习实战]决策树/" title="[机器学习实战]决策树">http://mantoudev.com/[机器学习实战]决策树/</a></p>
  <p><span>版权声明:</span>本博客所有文章除特别声明外，均采用 <i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/" target="_blank" title="Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)"> BY-NC-SA 3.0 许可协议</a>，转载请注明出处！</p>
</div>


      
    </div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>谢谢老板~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Mantou 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Mantou 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/机器学习/" rel="tag"># 机器学习</a>
          
            <a href="/tags/决策树/" rel="tag"># 决策树</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/[机器学习Lesson 4]多元线性回归/" rel="next" title="[机器学习Lesson 4]多元线性回归">
                <i class="fa fa-chevron-left"></i> [机器学习Lesson 4]多元线性回归
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/[大数据安全]Apache Kylin 安全配置(Kerberos)/" rel="prev" title="[大数据安全]Apache Kylin 安全配置(Kerberos)">
                [大数据安全]Apache Kylin 安全配置(Kerberos) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
  <div id="gitalk-container"></div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Mantou">
            
              <p class="site-author-name" itemprop="name">Mantou</p>
              <p class="site-description motion-element" itemprop="description">吭哧吭哧👨‍💻‍</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/mantoudev" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:mantoudev@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-简介"><span class="nav-text">1. 简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-决策树场景"><span class="nav-text">1.1 决策树场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#场景一：二十个问题"><span class="nav-text">场景一：二十个问题</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#场景二：邮件分类"><span class="nav-text">场景二：邮件分类</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-定义"><span class="nav-text">1.2 定义</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#2-决策树原理"><span class="nav-text">2. 决策树原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-工作原理"><span class="nav-text">2.1 工作原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-决策树开发流程"><span class="nav-text">2.2 决策树开发流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-决策树算法特点"><span class="nav-text">2.3 决策树算法特点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-实战案例"><span class="nav-text">3. 实战案例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-项目概述"><span class="nav-text">3.1 项目概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-开发流程"><span class="nav-text">3.2 开发流程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-收集数据"><span class="nav-text">(1) 收集数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-准备数据"><span class="nav-text">(2) 准备数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（3）-分析数据"><span class="nav-text">（3） 分析数据</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#计算给定数据集的香农熵的函数"><span class="nav-text">计算给定数据集的香农熵的函数</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#按照给定特征划分数据集"><span class="nav-text">按照给定特征划分数据集</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#选择最好的数据集划分方式"><span class="nav-text">选择最好的数据集划分方式</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（4）训练算法"><span class="nav-text">（4）训练算法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（5）测试算法"><span class="nav-text">（5）测试算法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（6）使用算法"><span class="nav-text">（6）使用算法</span></a></li></ol></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mantou</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">38.4k</span>
  
</div>


<!--<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>-->



  <!--<span class="post-meta-divider">|</span>-->



  <!--<div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>-->




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="/js/src/md5.js"></script>
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
		var gitalk = new Gitalk({
		  clientID: '166772c775bb840c4d30',
		  clientSecret: '705cf1b571902b10c6e103604a718ff2ee1dd108',
		  repo: 'blog-comments',
		  owner: 'mantoudev',
		  admin: ['mantoudev'],
		  id: md5(location.pathname),
		  distractionFreeMode: 'true'
		})
		gitalk.render('gitalk-container')
       </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("1ksH739lNLQGmPbiKV7caYHV-gzGzoHsz", "kgyOnl48BVfVTzUF8NaU6gFY");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
